package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.SignIn;
import cn.wolfcode.trip.base.mapper.SignInMapper;
import cn.wolfcode.trip.base.service.ISignInService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SignInServiceImpl implements ISignInService {

    private final SignInMapper signInMapper;

    @Autowired
    public SignInServiceImpl(SignInMapper signInMapper) {
        this.signInMapper = signInMapper;
    }

    /**
     * 新增签到对象
     *
     * @param entity 签到对象
     */
    @Override
    public void saveOrUpdate(SignIn entity) {
        // 当前系统时间, 时间中的日
        int day = new Date().getDate();
        SignIn signIn = signInMapper.selectCurrentState(entity.getUserId());
        // 最新签到时间, 最新签到时间中的日
        if (signIn == null) {
            entity.setCount(1);
            entity.setIntegral(3);
        } else {
            int timeDay = signIn.getTime().getDate();
            if (day - timeDay > 1) {
                // 当前系统时间与最新签到时间差大于1, 不是连续签到, 把当前连续签到的次数重置为1
                entity.setCount(1);
            } else {
                entity.setCount(signIn.getCount() + 1);
            }
            entity.setIntegral(signIn.getIntegral() + 3);
        }
        entity.setTime(new Date());
        signInMapper.insert(entity);
        if (signIn != null) {
            signInMapper.updateByPrimaryKey(signIn);
        }
    }

    /**
     * 通过用户id查询当前用户的积分情况
     *
     * @param userId 用户id
     * @return 积分对象
     */
    @Override
    public List<SignIn> get(Long userId) {
        return signInMapper.selectByPrimaryKey(userId);
    }

    /**
     * 查询最新的签到信息
     *
     * @return 签到对象
     */
    @Override
    public SignIn selectCurrentState(Long userId) {
        return signInMapper.selectCurrentState(userId);
    }

    /**
     * 更新积分
     */
    @Override
    public void updateIntegral(Long id, Integer integral) {
        SignIn signIn = new SignIn();
        signIn.setId(id);
        signIn.setIntegral(integral);
        signInMapper.updateByPrimaryKey(signIn);
    }
}
